/*!
 * 我的图片选择模块
 * @author Sherlock 
 * -----------------------
 * imagesChooseCallback 选择确认后的回调
 */
require( './style.less' );
define( [ 'jquery',
  'require',
  'message',
  'bigwe_utils',
  'api',
  'bootstrap'
], function( $ ) {
  var returnParam = {};
  var ShowTitleMessage = require( 'message' );
  var showTime = ShowTitleMessage.showTime;
  var BIGWE_API = require( 'api' );
  var bu = require( 'bigwe_utils' );

  var wechartImgCheck = bu.wechartImgCheck;
  var $me = returnParam.$selector = $( '#my_images_choose' );

  var size = 20,
    pageNo = 1;
  var isLoading = 0,
    isNoData = 0;

  $me.on( 'shown.bs.modal', function() {
    if ( $( '#images_list .img_detail', this ).length ) return;

    ajaxRequest();

  } ).on( 'click', '.img_detail', function() {
    $( this ).addClass( 'selected' ).siblings().removeClass( 'selected' );
  } ).on( 'click', '#images_sure', function() {

    var selected = $( '.img_detail.selected', $me );

    if ( selected.length ) {

      if ( typeof returnParam.imagesChooseCallback === 'function' ) {
        returnParam.imagesChooseCallback.call( $me, $( 'img', selected ).attr( 'src' ) || '', selected.data() );
      }

      $me.modal( 'hide' );

    } else {
      ShowTitleMessage.showWarning( '请选择一个图片', showTime );
    }
  } );

  $( '#images_list', $me ).scrollMax( function() {

    if ( !isLoading && !isNoData ) {

      pageNo++;
      ajaxRequest();

    }

  } );

  function ajaxRequest( fn ) {
    isLoading = 1;
    $( '.spinner', $me ).show();
    $.ajax( {
      type: 'post',
      url: BIGWE_API.COMMON.GET_MATERIAL_IMAGES,
      data: {
        size: size,
        start: ( pageNo - 1 ) * size
      },
      success: function( data ) {
        data = typeof data === 'string' ? $.parseJSON( data ) : data;
        if ( data.ret ) {
          ShowTitleMessage.showWarning( data.msg || '未知的错误', showTime );
          return;
        }
        if ( !data.data.length ) {
          ShowTitleMessage.showWarning( '没有数据了', showTime );
          isNoData = 1;
          return;
        }

        var appendHtml = '';

        for ( i in data.data ) {
          $( '#images_list', $me ).append( getImagesHtml( data.data[ i ] ) );
        }

        if ( fn ) {
          fn.call( $me );
        }

      },
      complete: function() {
        isLoading = 0;
        $( '.spinner', $me ).hide();
      }
    } );
  }

  function getImagesHtml( imgObj ) {

    var html = '';

    html += '<div class="img_detail">';
    html += '<div class="mask"><span class="glyphicon glyphicon-ok ok_icon"></span></div>';
    html += '<img src="' + wechartImgCheck( imgObj.image ) + '">';
    html += '</div>';

    return $( html ).data( imgObj );
  }

  return returnParam;
} );
